import { reqAttrList, reqCategory1, reqCategory2, reqCategory3, reqDeleteAttr } from '@/api/attr'
import { Button, Card, Form, Input, message, Modal, Popconfirm, Select, Table, Tag, Typography } from 'antd'
import { ColumnsType } from 'antd/lib/table'
const { Option } = Select;
import {
  EditOutlined,
  DeleteOutlined,
  FormOutlined,
  CheckOutlined,
} from '@ant-design/icons';

import React, { useEffect, useState } from 'react'

function index() {

  const [loading, setloading] = useState(false)

  // 弹窗是否显示
  const [isModal , setIsModal] = useState(false)

  // 表单 每列数据
  const columns: ColumnsType<any> = [
    {
      title: '序号',
      align: "center",
      key: 'index',
      render(values, rows, index) {
        return index + 1
      }
    },
    {
      title: '属性名称',
      align: "center",
      key: 'index',
      render(values) {
        return values.attrName
      }
    },
    {
      title: '属性名称列表',
      align: "center",
      key: 'index',
      render(row) {
        return (
          <div className='tagList'>
            {
              row.attrValueList.map((item: any) => {
                return <Tag key={item.id}>{item.valueName}</Tag>
              })
            }
          </div>
        )
      }
    },
    {
      title: '操作',
      align: "center",
      key: 'index',
      render: (row) => (
        <>
          <Button type="primary" icon={<EditOutlined />} style={{ marginRight: '3px' }} onClick={() => updateAttr(row)}>
            修改
          </Button>
          <Button danger icon={<DeleteOutlined />} onClick={() => deleteAttr(row.id)}>
            删除
          </Button>
        </>
      )
    },
  ]


  // 更新属性值时用到的表单数据
  const updateAttrCols:ColumnsType<any> = [
    {
      title: '序号',
      align: "center",
      key: 'index',
      render(values, rows, index) {
        return index + 1
      }
    },
    {
      title: '属性值名称',
      align: "center",
      key: 'index',
      render:(row)=> {
        const isShow = isShowFn(row)
        return (
          isShow?<Input value={row.valueName}/> :<span>{row.valueName}</span>
        )
      }
    },
    {
      title: '操作',
      align: "center",
      key: 'index',
      render: (row) => (
        <>
          <Typography.Link onClick={() => deleteAttrVaule(row.id)} style={{ marginRight: 8 }}>
            删除属性值
          </Typography.Link>
          <Typography.Link onClick={() => enterAttrValue(row)} style={{ marginRight: 8 }}>
            保存属性值
          </Typography.Link> 
          <Typography.Link onClick={() => updateAttrValue(row)} style={{ marginRight: 8 }}>
            修改属性值
          </Typography.Link>


          

        </>
      )
    },  
  ]




  // 三级联动列表
  const [categoryList, setcategoryList] = useState({
    category1List: [],
    category2List: [],
    category3List: []
  })

  // 三级联动id
  const [categoryId, setcategoryId] = useState({
    category1id: 0,
    category2id: 0,
    category3id: 0
  })


  // 封装请求一级分类请求
  const getCategory1 = async () => {
    const res = await reqCategory1()
    setcategoryList({
      category1List: res,
      category2List: [],
      category3List: []
    })
    form.resetFields([
      
    ])
  }

  // 封装获取二级分类列表请求
  const getCategory2 = async (value: number) => {
    const res = await reqCategory2(value)
    // 改变三级联动列表
    setcategoryList({
      ...categoryList,
      category2List: res,
      category3List: []
    })
    setcategoryId({
      ...categoryId,
      category1id: value
    })
    // 清理表单项
    form.resetFields([

    ])
  }

  useEffect(()=>{

  },[])

  // 封装获取三级分类列表请求
  const getCategory3 = async (value: number) => {
    const res = await reqCategory3(value)
    setcategoryList({
      ...categoryList,
      category3List: res
    })
    setcategoryId({
      ...categoryId,
      category2id: value,
    })
  }

  // 商品属性列表 
  const [attrlist, setattrlist] = useState([])



  // 获取商品属性列表
  const getAttrList = async (value: number) => {
    setcategoryId({
      ...categoryId,
      category3id: value
    })
    const res = await reqAttrList(categoryId.category1id, categoryId.category2id, value)
    
    setattrlist(res)
  }

  

  // 新增或修改属性的初始值
  const [newattrdata, setnewattrdata] = useState<any>({
    attrName:'',
    categoryId:categoryId.category3id,
    categoryLevel : 3,  // 固定值
    attrValueList:[] , // 商品属性值列表
  })


  // 修改属性
  const updateAttr = (row: any) => {
    row.attrValueList.forEach((item:any)=> item.isEdit = isedit) // 添加isEdit属性 方便更新属性值
    setnewattrdata({
      attrValueList:row.attrValueList,
    })
    setIsModal(true)
  }

  // 新增属性名
  const addAttr = () =>{
    setIsModal(true)
  }

  // 添加属性值
  const addAttrValue = () => {

  }


  const isShowFn = (row:any) =>{
    console.log(row);
    
    return row.valueName === row.isEdit
  }

  const [isedit , setisedit] = useState('')

  // 修改属性值
  const updateAttrValue = (row:any) => {

    setisedit(row)
  }


  // 删除属性值
  const deleteAttrVaule = (id:number) => {
    
  }

  // 保存属性值
  const enterAttrValue = (row:any) => {
    row.isEdit = true
  }



  // 提交表单事件  
  const onFinsh = () => {
    setIsModal(false)
  }

  // 表单关闭事件
  const modalCancel = () => {
    setIsModal(false)
  }



  // 封装 删除属性方法
  const deleteAttr = async(id: number) => {
    await reqDeleteAttr(id)
    getAttrList(categoryId.category3id)
    message.success('删除成功')
  }


  useEffect(() => {
    getCategory1()
  }, [])




  const [form] = Form.useForm() // 实例化form
  return (
    <div>
      <Card size="small" style={{ width: 1000, margin: 20 }}>
        <Form
          name="basic"
          form={form}
          layout={'inline'}
        >
          <Form.Item
            label="一级菜单"
          >
            <Select style={{ width: 200 }} onChange={getCategory2}>
              {categoryList.category1List.map((item: any) => {
                return (
                  // const { Option } = Select;  一定要单独引入
                  <Option value={item.id} key={item.id}>
                    {item.name}
                  </Option>
                )
              })}
            </Select>
          </Form.Item>

          <Form.Item
            label="二级菜单"
          >
            <Select style={{ width: 200 }} onChange={getCategory3}  >
              {categoryList.category2List.map((item: any) => {
                return (
                  <Option value={item.id} key={item.id}>
                    {item.name}
                  </Option>
                )
              })}
            </Select>
          </Form.Item>
          <Form.Item
            label="三级菜单"
          >
            <Select style={{ width: 200 }} onChange={getAttrList} >
              {categoryList.category3List.map((item: any) => {
                return (
                  <Option value={item.id} key={item.id}>
                    {item.name}
                  </Option>
                )
              })}
            </Select>
          </Form.Item>
        </Form>

        <p style={{ marginTop: 30, marginBottom: 30 }}>
          <Button 
            // disabled={categoryId.category3id=== 0} 
            type="primary"
            onClick={addAttr}
          >新增属性</Button>
        </p>


        <Table
          rowKey={"id"}
          loading={loading}
          columns={columns}
          dataSource={attrlist}
          pagination={false}
        />


        <Modal
          title="添加品牌"
          width={'980px'}
          maskClosable={true}
          visible={isModal}
          footer={null}
        >
          <Form
            name="basic"
            form={form}
            onFinish={onFinsh}
          >
            <Form.Item
              label="属性名称"
              name="valueName"
            >
              <Input style={{width:500}} placeholder="请输入属性名" />
            </Form.Item>


            <Form.Item >
              <Button type="primary" onClick={addAttrValue}>
                添加属性值
              </Button>
              <Button htmlType="button" onClick={modalCancel}>
                取消
              </Button>
            </Form.Item>
            
            <Form.Item>
              <Table
                rowKey={"id"}
                loading={loading}
                columns={updateAttrCols}
                dataSource={newattrdata.attrValueList}
                pagination={false}
              />

            </Form.Item>


            <Form.Item >
              <Button type="primary" htmlType="submit">
                提交
              </Button>
              <Button htmlType="button" onClick={modalCancel}>
                取消
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </Card>

    </div>
  )
}

export default index